from django.shortcuts import render
from .models import *
from .serializer import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from users.models import *
from users.serializer import *
from werkzeug.security import generate_password_hash,check_password_hash
from utlis.utils_token import login_token
from rest_framework.viewsets import ModelViewSet
import json
from utlis.user_login import check_login

# Create your views here.


# 获取登录用户菜单
class MenuModelAPIView(ModelViewSet):
    queryset = MenuModel.objects.filter(is_delete=False).all()
    serializer_class = MenuSer

    @check_login
    def list(self, request, *args, **kwargs):
        try:
            user_id  = request.user
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "没有该用户"
                })
            print('user_id', user.position_id)
            position = PositionModel.objects.filter(id=user.position_id).first()
            print('position_id role', position.role_id)
            menu_role = MenuRoleModel.objects.filter(role_id=position.role_id).all()
            menu_role_ser = MenuRoleSer(menu_role, many=True).data
            menu_role_list = json.loads(json.dumps(menu_role_ser))
            print("菜单", menu_role_list)
            menu_list_data = []
            for i in menu_role_list:
                menu = MenuModel.objects.filter(is_delete=False, id=i['menu_id']).first()
                print('ment>>>', menu)
                menu_ser = MenuSer(menu).data
                menu_list_data.append(menu_ser)
            for j in menu_list_data:
                menu_class = MenuSubClassModel.objects.filter(menu_id=j['id']).first()
                menu_class_ser = MenuSubClassSer(menu_class).data
                j["ment_class"] = menu_class_ser
            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取菜单成功！",
                'menu_data': menu_list_data
            })
        except Exception as e:
            print("错误》》", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 获取轮播图
class SlideshowView(ModelViewSet):
    queryset = SlideshowModel.objects.filter(is_delete=False).all()
    serializer_class = SlideshowSer